var G_windowTitle;
var form;
var G_id;
$(document).ready(function () {
  initLayui();
  initOil();
});


var curOilId = '';


function initOil() {
  AjaxRequest('/oiltank/select', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;

      $(".oil-list").empty().append(data.reduce((x, y) => {

        return x + `<div class="oil-item" data-id="${y.id}">${y.name}</div>`

      }, '<div class="oil-item active" data-id="">全部油罐</div>'))

      var str = '<option value="">请选择</option>';
      $.each(data, function (i, val) {
        str += `<option value="${val.id}">${val.name}</option>`;
      });
      $('#gatewaySsId').empty().append(str);



      $('.oil-item').click(function (e) {
        $(e.currentTarget).addClass('active').siblings().removeClass('active');

        curOilId = $(e.currentTarget).data().id;
        initTable()

      })

      $('.oil-item').eq(0).click()


    }
  }
}


function initLayui() {
  layui.use(['form'], function () {
    form = layui.form;

    form.on('submit(filter)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(search)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(save)', function (data) {
      var params = {
        id: G_windowTitle == '新增' ? null : G_id,
        name: data.field.name,
        code: data.field.code,
        gatewaySsId: data.field.gatewaySsId,
        gatewayMaId: data.field.gatewayMaId,
        startAddr: data.field.startAddr,
        oilId: curOilId,
        stopAddr: data.field.stopAddr,
        openAddr: data.field.openAddr,
        closeAddr: data.field.closeAddr,
        maAddr: data.field.maAddr,
        seqNo: data.field.seqNo,
      };
      save(params);
      return false;
    });

  });
}

// 新增编辑弹窗
function showWindow(title, res) {

  if (res) {
    curOilId = res.oilId
  }


  if (curOilId == "") {
    layer.msg('请先左侧列表选择所属油罐')
  } else {
    layer.open({
      type: 1,
      title: title,
      skin: 'default-class',
      area: ['6rem', 'auto'],
      // shade: false,
      move: false,
      closeBtn: 2,
      id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
      content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;">
                  <div class="layui-form-item">
                    <label class="layui-form-label">阀门名称</label>
                    <div class="layui-input-block">
                      <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">编号</label>
                    <div class="layui-input-block">
                      <input type="text" name="code" autocomplete="off" class="layui-input" lay-verify="required">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">阀门开关网关</label>
                    <div class="layui-input-block">
                      <select id="gatewaySsId" name="gatewaySsId" lay-verify="required"></select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">本地丨远程网关</label>
                    <div class="layui-input-block">
                      <select id="gatewayMaId" name="gatewayMaId" lay-verify="required"></select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">打开地址下行</label>
                    <div class="layui-input-block">
                      <input type="text" name="startAddr" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">关闭地址下行</label>
                    <div class="layui-input-block">
                      <input type="text" name="stopAddr" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">全开地址</label>
                    <div class="layui-input-block">
                      <input type="text" name="openAddr" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">全关地址</label>
                    <div class="layui-input-block">
                      <input type="text" name="closeAddr" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">本地丨远程地址</label>
                    <div class="layui-input-block">
                      <input type="text" name="maAddr" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">阀门序号</label>
                    <div class="layui-input-block">
                      <input type="text" name="seqNo" autocomplete="off" lay-verify="required|number" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item form-btn" style="text-align:center">
                    <div class="layui-input-block" style="margin-left: 0;">
                      <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                    </div>
                  </div>
                </form>`, //这里content是一个普通的String
      success: function (layero, index) {
        initRoleSelect();
        G_windowTitle = title;
        setTimeout(() => {
          if (title == '编辑') {
            G_id = res.id;
            //给表单赋值
            form.val('saveForm', {
              name: res.name,
              code: res.code,
              gatewaySsId: res.gatewaySsId,
              gatewayMaId: res.gatewayMaId,
              startAddr: res.startAddr,
              oilId: curOilId,
              stopAddr: res.stopAddr,
              openAddr: res.openAddr,
              closeAddr: res.closeAddr,
              maAddr: res.maAddr,
              seqNo: res.seqNo,
            });
          }
        }, 100);
      },
      cancel: function (index, layero) {
        curOilId = $('.oil-item.active').data().id;
      }
    });
  }


}

function initRoleSelect() {
  AjaxRequest('/gateway/select?type=', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;
      const ssArr = data.filter(item => item.type == 2);
      const maArr = data.filter(item => item.type == 1);

      $('#gatewaySsId').empty().append(ssArr.reduce((x, y) => {
        return x + `<option value="${y.id}">${y.name}</option>`;
      }, '<option value="">请选择</option>'));

      $('#gatewayMaId').empty().append(maArr.reduce((x, y) => {
        return x + `<option value="${y.id}">${y.name}</option>`;
      }, '<option value="">请选择</option>'));

      form.render();
    }
  }
}

// 保存表单
function save(data) {
  AjaxRequest('/valve/save', callBack, data, 'post');

  function callBack(result) {
    if (result.status == 200) {
      initTable();
      layer.closeAll();
      layer.msg('保存成功！');
    } else {
      layer.msg('保存失败！');
    }
  }
}

function initTable() {

  layui.use('table', function () {
    var table = layui.table;
    var height = $('.search-content').innerHeight() - 20;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/valve/list',
      where: {
        name: $('#search-name').val(),
        oilId: curOilId
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result ? res.result.total : 0, //解析数据长度
          data: res.result ? res.result.data : [], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '名称',
            align: 'center',
          },
          {
            field: 'code',
            title: '编号',
            align: 'center',
          },
          {
            field: 'oilName',
            title: '所属油罐',
            align: 'center',
          },
          {
            field: 'maStatusDesc',
            title: '本地丨远程状态',
            align: 'center',
            templet: $('#switch-status'),
          },
          {
            field: 'ssStatusDesc',
            title: '阀门开关',
            align: 'center',
          },
          {
            field: 'seqNo',
            title: '阀门序号',
            align: 'center',
          },
          {
            field: '',
            title: '操作',
            align: 'center',
            width: 200,
            templet: function (d) {
              let res = JSON.stringify(d);
              return `<div class="table-tool">
                        <div onclick='showWindow("编辑",${res})'>
                          <img src="../static/img/edit.png">编辑
                        </div>
                        <div onclick='showDelWindow(${res})'>
                          <img src="../static/img/delete.png">删除
                        </div>
                      </div>`;
            },
          },
        ],
      ],
    });
  });
}

function showDelWindow(res) {
  layer.confirm(
    '确认是否删除?',
    {
      btn: ['确认', '取消'], //按钮
    },
    function () {
      AjaxRequest('/valve/delete?id=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          initTable();
          layer.closeAll();
          layer.msg('删除成功!');
        }
      }
    }
  );
}
